package com.dorukdestan.p2pshare.gui;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

import com.dorukdestan.p2pshare.logger.Logger;
import com.dorukdestan.p2pshare.model.Constants;
import com.dorukdestan.p2pshare.network.FileTransferOperations;
import com.dorukdestan.p2pshare.network.FileTransferQueryServer;
import com.dorukdestan.p2pshare.network.QueryClient;
import com.dorukdestan.p2pshare.network.QueryServer;
import com.dorukdestan.p2pshare.storage.PeerList;
import com.dorukdestan.p2pshare.util.FileOperations;

public class ShareMeConsole {
	
	public static void main(String[] args) throws UnknownHostException {
		
		Logger logger = new Logger(ShareMeConsole.class);
		
		//Start QueryServer
		QueryServer queryServer = new QueryServer();
		Thread queryServerThread = new Thread(queryServer);
		queryServerThread.start();
		
		//Start FileTransferQeryServer
		FileTransferQueryServer fileTransferQueryServer = new FileTransferQueryServer();
		Thread fileTransferQueryServerThread = new Thread(fileTransferQueryServer);
		fileTransferQueryServerThread.start();

		//Find nearest peers
		PeerList.updateNearestPeers();
		PeerList.waitUntillReady();
		
		Scanner userInput = new Scanner(System.in);
		userInput.useDelimiter("\n");
		
		while(true){
			System.out.print("Write command: ");
			
			//TODO call fixProgram() here to ensure servers are up and peersList is set 
			
			String inputString = userInput.next();
			String[] inputParameters = inputString.split(" ");

			if(inputParameters[0].equalsIgnoreCase("adddir")){
				if(inputParameters.length == 2){

					if(FileOperations.addDirectory(inputParameters[1])){
						logger.info("Directory added");	
					}
				}
				else
					logger.error("Path argument is required!");
			}
			else if(inputParameters[0].equalsIgnoreCase("search")){
				if(inputParameters.length == 3){
					QueryClient.searchRemote(inputParameters[1], inputParameters[2]);
				}
				else
					logger.error("Search arguments is required!");
			}
			else if(inputParameters[0].equalsIgnoreCase("download")){
				if(inputParameters.length == 2){
					FileTransferOperations.startNewDownload(inputParameters[1]);//fileHash
				}
				else
					logger.error("Download argument is required!");
			}
			else if(inputParameters[0].equalsIgnoreCase("exit")){
				System.out.println("Terminated by user.");
				System.exit(0);
			}
		}
	}
}
